package com.zoiz.util;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.util.Properties;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.sql.DataSource;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.zoiz.dbutils.ThreadHolder;
import com.zoiz.plus.extend.CommonUtils;
import com.zoiz.plus.extend.DBException;

/**
 * 初始化
 * 
 * @author Administrator
 * 
 */
public class ConfigurationsInitialization implements ServletContextListener {
	private final Log log = LogFactory.getLog(getClass());

	/*
	 * (non-Javadoc)
	 * 
	 * @seejavax.servlet.ServletContextListener#contextDestroyed(javax.servlet.
	 * ServletContextEvent)
	 */
	@Override
	public void contextDestroyed(ServletContextEvent sce) {

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.ServletContextListener#contextInitialized(javax.servlet
	 * .ServletContextEvent)
	 */
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		try {
			String webAppPath = CommonUtils.getWebAppPath(sce
					.getServletContext());
			log.info("load c3p0.properties......");
			Properties props = CommonUtils.readProperties(webAppPath
					+ "WEB-INF/c3p0.properties");
			Properties cp_props = new Properties();
			for (Object key : props.keySet()) {
				String skey = (String) key;
				if (skey.startsWith("jdbc.")) {
					String name = skey.substring(5);
					cp_props.put(name, props.getProperty(skey));
				}
			}
			DataSource dataSource = (DataSource) Class.forName(
					cp_props.getProperty("datasource")).newInstance();
			if (dataSource.getClass().getName().indexOf("c3p0") > 0) {
				// Disable JMX in C3P0
				System.setProperty(
						"com.mchange.v2.c3p0.management.ManagementCoordinator",
						"com.mchange.v2.c3p0.management.NullManagementCoordinator");
			}
			BeanUtils.populate(dataSource, cp_props);
			Configurations.setDs(dataSource);
			Connection conn = ThreadHolder.getCurrentConnection();
			DatabaseMetaData mdm = conn.getMetaData();
			log.info("Connected to " + mdm.getDatabaseProductName() + " "
					+ mdm.getDatabaseProductVersion());
			DbUtils.closeQuietly(conn);
		} catch (Exception e) {
			// TODO: handle exception
			throw new DBException(e);
		}
	}

}